<?php


namespace app\api\controller\v1;

use app\common\exception\ForbiddenException;
use app\common\exception\ParameterFailedException;
use app\common\menu\Common;
use app\common\service\Redis;
use app\common\validate\BaseValidate;
use think\Controller;

class V1BaseController extends Controller
{
    protected $userId;
    protected $userInfo;
    protected $accessToken;
    protected $page;
    protected $limit;

    //protected $middleware = ['base'];

    public function initialize()
    {
        parent::initialize();

        #验证首要参数
        $this->page  = request()->get()['page'] ?? 1;
        $this->limit = request()->get()['limit'] ?? 10;
        (new BaseValidate())->goCheck('baseParams', ['page' => $this->page, 'limit' => $this->limit]);

        $header = request()->header();
        $this->accessToken = @$header['access_token'];
        $userId            = Redis::getRedis()->get('user:atoken:'.$this->accessToken);
        if ($userId === false) {
            //throw new ForbiddenException();
        }else{
            #给token续时
            Redis::getRedis()->expire('user:atoken:'.$this->accessToken, Common::USER_ACCESS_TOKEN_EXPIRE);
        }

        $this->userId   = $userId;
        $this->userInfo = Redis::getRedis()->hGetAll('user:'.$this->userId);
    }

    public function authentication(): void
    {

    }

    final protected function getParams($name)
    {
        $param = \request()->param();
        if (is_array($name)) {
            $return = [];
            foreach ($name as $item) {
                $example = @$param[$item];
                if ($example === null) {
                    $return[$item] = null;
                } elseif ($example === 0) {
                    $return[$item] = 0;
                } else {
                    $return[$item] = self::guolvParam($example);
                }
            }
            foreach ($return as $item) {
                if (preg_match('/(and|or|union|where|limit|group by|select|hex|substr)/i', $item)) {
                    throw new BaseException(['msg' => "参数错误"]);
                }
            }
            return $return;
        } else {
            if (is_string($name)) {
                $result = @$param[$name];
                $result = self::guolvParam($result);
                if (preg_match('/(and|or|union|where|limit|group by|select|hex|substr)/i', $result)) {
                    throw new BaseException(['msg' => "参数错误"]);
                }
                return $result;
            }
        }
    }

    public static function guolvParam($value)
    {
        if (!get_magic_quotes_gpc()) {
            // 进行过滤
            $value = addslashes($value);
        }
        $value = str_replace("_", "\_", $value);
        $value = str_replace("%", "\%", $value);
        $value = nl2br($value);
        $value = htmlspecialchars($value);
        return $value;
    }
}